package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserInfoResolver;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息解析器
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //指定该解析器能解析参数类型, 只有匹配了才会执行这个解析器
    //此处表示能解析 UserInfo 类型
    //返回true 才执行
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //必须有参数的类型是UserInfo 和 参数上注解是 UserInfoResolver
        return methodParameter.getGenericParameterType()==UserInfo.class &&
                methodParameter.hasParameterAnnotation(UserInfoResolver.class);
    }

    //执行解析器,获取用户信息
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取请求信息
        HttpServletRequest request =nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //从请求头获取token
        String token = request.getHeader("token");
        //获得用户信息
        UserInfo user = userInfoRedisService.getRedisUser(token);
        return user;
    }
}
